//
//  WNDownloadManager.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/25.
//

import UIKit

import Alamofire

class WNDownloadManager: NSObject {
        
    static let shared = WNDownloadManager()
    
    let fileManager = FileManager.default

    var fileUrl = ""

    var bookId = ""

    var chapterId = 0
    
    var isLoading = false

    var downloadRequest: DownloadRequest?
        
    var downloadClosure: IntClosure?
    
    // 必须是全局变量（坑）
    var docIntVC: UIDocumentInteractionController?
    
    func creatDowmloadRequest(_ bid: String, _ cid: Int, fileStr: String) {
        if isLoading {
            WNHUD.wn_show("has book is downloading")
            return
        }
        resetDownload()
        bookId = bid
        chapterId = cid
        fileUrl = fileStr
        startDownloadFile()
    }
    
    // 取消下载
    @objc func resetDownload() {
        downloadRequest?.cancel()
        downloadRequest = nil
        bookId = ""
        chapterId = 0
        fileUrl = ""
        isLoading = false
    }
    
    // 开始下载
    @objc func startDownloadFile() {
        let filePath = NSHomeDirectory() + "/Documents/Book/\(bookId)"
        if !fileManager.fileExists(atPath: filePath) {
            try? fileManager.createDirectory(atPath: filePath, withIntermediateDirectories: true, attributes: nil)
        }
        let chapterPath = "\(filePath)/\(chapterId).txt"
        if fileManager.fileExists(atPath: chapterPath) {
            try? fileManager.removeItem(atPath: chapterPath)
        }
        let destination: DownloadRequest.Destination = { _, response in
            let fileURL = URL(fileURLWithPath: chapterPath)
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }
        downloadRequest = Session.default.download(fileUrl, to: destination)
        downloadRequest?.downloadProgress { (pro) in
            if pro.fractionCompleted*100 >= 99 {
                WNHUD.wn_hide()
            }
        }
        downloadRequest?.responseData(completionHandler: downloadResponse)
        DispatchQueue.main.async {
            self.downloadClosure?(1)
        }
        isLoading = true
    }
    
    //根据下载状态处理
    func downloadResponse(response: AFDownloadResponse<Data>) {
        switch response.result {
        case .success:
            DispatchQueue.main.async {
                if let data = response.value, data.count > 1000 {
                    if let _ = response.fileURL {
                        self.downloadClosure?(2)
                        self.isLoading = false
                        WNHUD.wn_show("download completed")
                    }
                }else {
                    self.downloadClosure?(0)
                    self.resetDownload()
                    WNHUD.wn_show("download failed")
                }
            }
        case .failure:
            downloadClosure?(0)
            self.resetDownload()
            WNHUD.wn_show("download interrupted")
        }
    }
    
    func geChapterStr(_ bid: String, _ cid: Int) -> String {
        let chapterPath = NSHomeDirectory() + "/Documents/Book/\(bid)/\(cid).txt"
        if fileManager.fileExists(atPath: chapterPath) {
            if let chapterStr = try? String.init(contentsOfFile: chapterPath, encoding: .utf8) {
                return chapterStr
            }
            return ""
        }else {
            return ""
        }
    }
}
